<template>
  <div class="device-pricing-form">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span class="title">{{ title }}</span>
          <div class="buttons">
            <el-button type="primary" @click="submitForm" :loading="submitLoading" v-if="!isViewMode">
              <el-icon><Check /></el-icon>提交
            </el-button>
            <el-button @click="goBack">
              <el-icon><Back /></el-icon>返回
            </el-button>
          </div>
        </div>
      </template>

      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" label-position="right" :disabled="isViewMode">
        <!-- 基本信息 -->
        <el-card class="base-info-card" shadow="never">
          <template #header>
            <div class="form-section-header">
              <el-icon><Document /></el-icon>
              <span>基本信息</span>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="项目名称" prop="projectId">
                <el-select v-model="form.projectId" placeholder="请选择设备类别" clearable class="full-width">
                  <el-option 
                    v-for="item in projectList" 
                    :key="item.id" 
                    :label="item.name" 
                    :value="item.id" 
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="设备类别" prop="type">
                <el-select v-model="form.type" placeholder="请选择设备类别" clearable class="full-width">
                  <el-option 
                    v-for="item in typeOptions" 
                    :key="item.dictLabel" 
                    :label="item.dictLabel" 
                    :value="item.dictLabel" 
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input 
                  v-model="form.remark" 
                  type="textarea" 
                  :rows="3" 
                  placeholder="请输入备注信息"
                  class="full-width"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 设备核价明细 -->
        <el-card class="device-details-card" shadow="never">
          <template #header>
            <div class="form-section-header">
              <el-icon><List /></el-icon>
              <span>设备核价明细</span>
            </div>
          </template>

          <!-- 只有当类型为堆垛机时才显示表格 -->
          <div v-if="form.type === '堆垛机'">
            <!-- 第一个表格：规格参数表 -->
            <h3 class="table-title">规格参数表</h3>
            <el-table :data="getSpecsTableData()" border class="device-details-table">
              <el-table-column prop="name" label="名称" min-width="150" align="center" />
              <el-table-column prop="unit" label="单位" width="80" align="center" />
              <el-table-column prop="defaultValue" label="数值(满载)" width="150" align="center">
                <template #default="scope">
                  <el-select
                    v-if="scope.row.name === '货叉类型'"
                    v-model="scope.row.defaultValue"
                    placeholder="请选择货叉类型"
                    :disabled="isViewMode"
                    class="full-width"
                    clearable
                  >
                    <el-option
                      v-for="item in forkTypeOptions"
                      :key="item.dictLabel"
                      :label="item.dictLabel"
                      :value="item.dictLabel"
                    />
                  </el-select>
                  <el-select
                    v-else-if="scope.row.name === '通讯方式'"
                    v-model="scope.row.defaultValue"
                    placeholder="请选择通讯方式"
                    :disabled="isViewMode"
                    class="full-width"
                    clearable
                  >
                    <el-option
                      v-for="item in commTypeOptions"
                      :key="item.dictLabel"
                      :label="item.dictLabel"
                      :value="item.dictLabel"
                    />
                  </el-select>
                  <el-select
                    v-else-if="scope.row.name === '定位方式'"
                    v-model="scope.row.defaultValue"
                    placeholder="请选择定位方式"
                    :disabled="isViewMode"
                    class="full-width"
                    clearable
                  >
                    <el-option
                      v-for="item in positionTypeOptions"
                      :key="item.dictLabel"
                      :label="item.dictLabel"
                      :value="item.dictLabel"
                    />
                  </el-select>
                  <el-select
                    v-else-if="scope.row.name === 'PLC'"
                    v-model="scope.row.defaultValue"
                    placeholder="请选择PLC"
                    :disabled="isViewMode"
                    class="full-width"
                    clearable
                  >
                    <el-option
                      v-for="item in plcTypeOptions"
                      :key="item.dictLabel"
                      :label="item.dictLabel"
                      :value="item.dictLabel"
                    />
                  </el-select>
                  <el-select
                    v-else-if="scope.row.name === '变频器'"
                    v-model="scope.row.defaultValue"
                    placeholder="请选择变频器"
                    :disabled="isViewMode"
                    class="full-width"
                    clearable
                  >
                    <el-option
                      v-for="item in inverterTypeOptions"
                      :key="item.dictLabel"
                      :label="item.dictLabel"
                      :value="item.dictLabel"
                    />
                  </el-select>
                  <el-select
                    v-else-if="scope.row.name === '光电开关'"
                    v-model="scope.row.defaultValue"
                    placeholder="请选择光电开关"
                    :disabled="isViewMode"
                    class="full-width"
                    clearable
                  >
                    <el-option
                      v-for="item in photoelectricTypeOptions"
                      :key="item.dictLabel"
                      :label="item.dictLabel"
                      :value="item.dictLabel"
                    />
                  </el-select>
                  <el-select
                    v-else-if="scope.row.name === '地面站数量'"
                    v-model="scope.row.defaultValue"
                    placeholder="请选择地面站数量"
                    :disabled="isViewMode"
                    class="full-width"
                    clearable
                  >
                    <el-option
                      v-for="item in stationNumOptions"
                      :key="item.dictLabel"
                      :label="item.dictLabel"
                      :value="item.dictLabel"
                    />
                  </el-select>
                  <el-select
                    v-else-if="scope.row.name === '滑触线安装方式'"
                    v-model="scope.row.defaultValue"
                    placeholder="请选择滑触线安装方式"
                    :disabled="isViewMode"
                    class="full-width"
                    clearable
                  >
                    <el-option
                      v-for="item in slideLineInstallOptions"
                      :key="item.dictLabel"
                      :label="item.dictLabel"
                      :value="item.dictLabel"
                    />
                  </el-select>
                  <el-select
                    v-else-if="scope.row.name === '能效等级要求'"
                    v-model="scope.row.defaultValue"
                    placeholder="请选择能效等级"
                    :disabled="isViewMode"
                    class="full-width"
                    clearable
                  >
                    <el-option
                      v-for="item in motorEfficiencyOptions"
                      :key="item.dictLabel"
                      :label="item.dictLabel"
                      :value="item.dictLabel"
                    />
                  </el-select>
                  <el-select
                    v-else-if="scope.row.name === '当前钢材价格'"
                    v-model="scope.row.defaultValue"
                    placeholder="请选择当前钢材价格"
                    :disabled="isViewMode"
                    class="full-width"
                    clearable
                  >
                    <el-option
                      v-for="item in steelPriceOptions"
                      :key="item.dictLabel"
                      :label="item.dictLabel"
                      :value="item.dictLabel"
                    />
                  </el-select>
                  <el-input
                    v-else
                    v-model="scope.row.defaultValue"
                    :disabled="isViewMode || scope.row.name === '提升行程'|| scope.row.name === '行走轮直径' || 
                    scope.row.name === '卷筒直径' || scope.row.name === '卷筒形式' || scope.row.name === '载货台类型' || 
                    scope.row.name === '立柱规格' || scope.row.name === '载货台重量' || scope.row.name === '立柱重量' || 
                    scope.row.name === '上下横梁重量' || scope.row.name === '附件重量' || scope.row.name === '提升总重' || 
                    scope.row.name === '行走总重过程' || scope.row.name === '行走总重' || 
                    scope.row.name === '需求转速' || scope.row.name === '需求扭矩' || scope.row.name === '需求功率' || 
                    scope.row.name === '需求转速2' || scope.row.name === '需求扭矩2' || scope.row.name === '需求功率2' || 
                    scope.row.name === '电机型号' || scope.row.name === '电机型号2' || 
                    scope.row.name === '输出功率2' || scope.row.name === '额定转速2' || scope.row.name === '额定扭矩2' || 
                    scope.row.name === '输出功率' || scope.row.name === '额定转速' || scope.row.name === '额定扭矩' || 
                    scope.row.name === '减速机型号' || scope.row.name === '减速机型号2' || scope.row.name === '提升电机' || 
                    scope.row.name === '行走电机' || scope.row.name === '基频频率2' || scope.row.name === '电机功率段2' || 
                    scope.row.name === '基频频率' || scope.row.name === '电机功率段' ||

                    scope.row.name === '堆垛机电控' "
                    :style="{backgroundColor: scope.row.color || 'transparent'}"
                    placeholder="请输入数值(满载)"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="price" label="价格（元）" width="150" align="center">
                <template #default="scope">
                  <el-input-number 
                    v-if="!isViewMode"
                    v-model="scope.row.price" 
                    :precision="scope.row.precision || 0" 
                    :step="1" 
                    :min="0" 
                    controls-position="right" 
                    style="width: 120px"
                    @change="updateSummarizedData"
                  />
                  <span v-else>{{ scope.row.price }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="remark" label="备注" min-width="150" align="center" />
            </el-table>

            <!-- 第二个表格：分项单价表 -->
            <h3 class="table-title pricing-title">分项单价表</h3>
            <el-table :data="getPricingTableData()" border class="device-details-table pricing-table">
              <el-table-column prop="name" label="名称" min-width="150" align="center" />
              <el-table-column prop="unit" label="单位" width="80" align="center" />
              <el-table-column prop="defaultValue" label="数值(满载)" width="150" align="center">
                <template #default="scope">
                  <el-select
                    v-if="scope.row.name === '行走电机'"
                    v-model="scope.row.defaultValue"
                    placeholder="请选择行走电机"
                    :disabled="isViewMode"
                    class="full-width"
                    clearable
                  >
                    <el-option
                      v-for="item in walkMotorOptions"
                      :key="item.dictLabel"
                      :label="item.dictLabel"
                      :value="item.dictLabel"
                    />
                  </el-select>
                  <el-select
                    v-else-if="scope.row.name === '提升电机'"
                    v-model="scope.row.defaultValue"
                    placeholder="请选择提升电机"
                    :disabled="isViewMode"
                    class="full-width"
                    clearable
                  >
                    <el-option
                      v-for="item in liftMotorOptions"
                      :key="item.dictLabel"
                      :label="item.dictLabel"
                      :value="item.dictLabel"
                    />
                  </el-select>
                  <el-select
                    v-else-if="scope.row.name === '货叉'"
                    v-model="scope.row.defaultValue"
                    placeholder="请选择货叉"
                    :disabled="isViewMode"
                    class="full-width"
                    clearable
                  >
                    <el-option
                      v-for="item in forkOptions"
                      :key="item.dictLabel"
                      :label="item.dictLabel"
                      :value="item.dictLabel"
                    />
                  </el-select>
                  <el-select
                    v-else-if="scope.row.name === '使用环境'"
                    v-model="scope.row.defaultValue"
                    placeholder="请选择使用环境"
                    :disabled="isViewMode"
                    class="full-width"
                    clearable
                  >
                    <el-option
                      v-for="item in envOptions"
                      :key="item.dictLabel"
                      :label="item.dictLabel"
                      :value="item.dictLabel"
                    />
                  </el-select>
                  <el-select
                    v-else-if="scope.row.name === '轨道类型'"
                    v-model="scope.row.defaultValue"
                    placeholder="请选择轨道类型"
                    :disabled="isViewMode"
                    class="full-width"
                    clearable
                  >
                    <el-option
                      v-for="item in railTypeOptions"
                      :key="item.dictLabel"
                      :label="item.dictLabel"
                      :value="item.dictLabel"
                    />
                  </el-select>
                  <el-select
                    v-else-if="scope.row.name === '单机监控'"
                    v-model="scope.row.defaultValue"
                    placeholder="请选择单机监控"
                    :disabled="isViewMode"
                    class="full-width"
                    clearable
                  >
                    <el-option
                      v-for="item in monitorOptions"
                      :key="item.dictLabel"
                      :label="item.dictLabel"
                      :value="item.dictLabel"
                    />
                  </el-select>
                  <el-select
                    v-else-if="scope.row.name === '巷道激光雷达'"
                    v-model="scope.row.defaultValue"
                    placeholder="请选择巷道激光雷达"
                    :disabled="isViewMode"
                    class="full-width"
                    clearable
                  >
                    <el-option
                      v-for="item in lidarOptions"
                      :key="item.dictLabel"
                      :label="item.dictLabel"
                      :value="item.dictLabel"
                    />
                  </el-select>
                  <el-select
                    v-else-if="scope.row.name === '铠甲/灭火器'"
                    v-model="scope.row.defaultValue"
                    placeholder="请选择铠甲/灭火器"
                    :disabled="isViewMode"
                    class="full-width"
                    clearable
                  >
                    <el-option
                      v-for="item in armorOptions"
                      :key="item.dictLabel"
                      :label="item.dictLabel"
                      :value="item.dictLabel"
                    />
                  </el-select>
                  <el-select
                    v-else-if="scope.row.name === '金属粉尘管控'"
                    v-model="scope.row.defaultValue"
                    placeholder="请选择金属粉尘管控"
                    :disabled="isViewMode"
                    class="full-width"
                    clearable
                  >
                    <el-option
                      v-for="item in dustOptions"
                      :key="item.dictLabel"
                      :label="item.dictLabel"
                      :value="item.dictLabel"
                    />
                  </el-select>
                  <el-select
                    v-else-if="scope.row.name === '滑触线'"
                    v-model="scope.row.defaultValue"
                    placeholder="请选择滑触线"
                    :disabled="isViewMode"
                    class="full-width"
                    clearable
                  >
                    <el-option
                      v-for="item in slideLineOptions"
                      :key="item.dictLabel"
                      :label="item.dictLabel"
                      :value="item.dictLabel"
                    />
                  </el-select>
                  <el-input
                    v-else
                    v-model="scope.row.defaultValue"
                    :disabled="isViewMode || scope.row.name === '机械本体'|| scope.row.name === '电控'
                    || scope.row.name === '机械安装调试'|| scope.row.name === '电控安装调试'
                    || scope.row.name === '其他非标'|| scope.row.name === '单台'
                    || scope.row.name === '合计'
                    || scope.row.name === '滑触线护板'|| scope.row.name === '运输'
                    "
                    :style="{backgroundColor: scope.row.color || 'transparent'}"
                    placeholder="请输入数值(满载)"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="price" label="价格（元）" width="150" align="center">
                <template #default="scope">
                  <el-input-number 
                    v-if="!isViewMode"
                    v-model="scope.row.price" 
                    :precision="scope.row.precision || 0" 
                    :step="1" 
                    :min="0" 
                    controls-position="right" 
                    style="width: 120px"
                    @change="updateSummarizedData"
                  />
                  <span v-else>{{ scope.row.price }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="remark" label="备注" min-width="150" align="center" />
            </el-table>
            
            <!-- 操作按钮 -->
            <div class="table-actions">
              <el-button type="primary" @click="calculatePricing" :loading="calculateLoading" v-if="!isViewMode">
                <el-icon><RefreshRight /></el-icon> 更新计算
              </el-button>
              <el-button type="success" @click="saveTableData" :loading="saveLoading" v-if="!isViewMode">
                <el-icon><Download /></el-icon> 保存数据
              </el-button>
            </div>
          </div>

          <!-- 当类型不是堆垛机时显示提示信息 -->
          <div v-else class="empty-table-tips">
            <el-empty description="请选择设备类型为堆垛机以显示核价明细表" />
          </div>

          <div class="summary-section">
            <div class="summary-item">
              <span class="label">合计金额：</span>
              <span class="value">{{ formatPrice(totalAmount) }}</span>
            </div>
          </div>
        </el-card>
      </el-form>
    </el-card>

    <!-- 物料选择器弹窗，已经不需要 -->
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, FormInstance, ElLoading } from 'element-plus'
import { 
  getDevicePricingDetailApi, 
  addDevicePricingApi, 
  updateDevicePricingApi,
  calculateStackerPricingApi
} from '@/api/devicePricing/index'
import type { DevicePricingPlan, DeviceDetailItem } from '@/api/devicePricing/type'
import { Check, Back, Document, List, Download, RefreshRight } from '@element-plus/icons-vue'
import { getListApi as getDictListApi } from "@/api/sysDictData"
import { SysDictData } from "@/api/sysDictData/type"
import { getSimpleProject } from "@/api/project"

// 定义props接收路由传递的display参数
const props = defineProps({
  display: {
    type: String,
    default: 'false'
  }
})

const route = useRoute()
const router = useRouter()
const formRef = ref<FormInstance>()
const submitLoading = ref(false)
const id = computed(() => route.params.id ? Number(route.params.id) : undefined)
const title = computed(() => {
  if (isViewMode.value) {
    return '查看设备核价'
  } else if (id.value) {
    return '编辑设备核价'
  } else {
    return '新增设备核价'
  }
})

// 是否为查看模式
const isViewMode = computed(() => route.query.display === 'true' || props.display === 'true')

// 设备类别选项
const typeOptions = ref<SysDictData[]>([])

// 新增：货叉类型字典选项
const forkTypeOptions = ref<SysDictData[]>([])

// 新增各字段的 options
const commTypeOptions = ref<SysDictData[]>([])
const positionTypeOptions = ref<SysDictData[]>([])
const plcTypeOptions = ref<SysDictData[]>([])
const inverterTypeOptions = ref<SysDictData[]>([])
const photoelectricTypeOptions = ref<SysDictData[]>([])
const stationNumOptions = ref<SysDictData[]>([])
const slideLineInstallOptions = ref<SysDictData[]>([])
const motorEfficiencyOptions = ref<SysDictData[]>([])
const steelPriceOptions = ref<SysDictData[]>([])

// 新增分项单价表相关 options
const walkMotorOptions = ref<SysDictData[]>([])
const liftMotorOptions = ref<SysDictData[]>([])
const forkOptions = ref<SysDictData[]>([])
const envOptions = ref<SysDictData[]>([])
const railTypeOptions = ref<SysDictData[]>([])
const monitorOptions = ref<SysDictData[]>([])
const lidarOptions = ref<SysDictData[]>([])
const armorOptions = ref<SysDictData[]>([])
const dustOptions = ref<SysDictData[]>([])
const slideLineOptions = ref<SysDictData[]>([])

// 表单数据
const form = reactive<DevicePricingPlan>({
  id: undefined,
  projectId: undefined,
  projectName: '',
  type: '',
  sumPrice: 0,
  remark: '',
  detailItems: []
})

// 监听设备类型变化
watch(() => form.type, (newValue) => {
  if (newValue === '堆垛机') {
    // 当类型为堆垛机时，清空原来的明细项，避免提交时包含不需要的数据
    form.detailItems = []
    
    
    // 计算初始总价
    updateSummarizedData()
  } else {
    // 清空表格数据
    form.detailItems = []
    form.sumPrice = 0
  }
})

// 表单校验规则
const rules = {
  projectId: [{ required: true, message: '请选择项目', trigger: 'change' }],
  type: [{ required: true, message: '请选择设备类别', trigger: 'change' }]
}

// 物料选择相关变量（不再需要，但保留变量避免引用错误）
const materialDialogVisible = ref(false)
const selectedMaterials = ref<any[]>([])

// 合计金额
const totalAmount = computed(() => form.sumPrice || 0)

// 格式化金额
const formatPrice = (price: number | string | undefined) => {
  if (price === undefined || price === null) return '¥0.00'
  const numPrice = typeof price === 'string' ? parseFloat(price) : price
  if (isNaN(numPrice)) return '¥0.00'
  return `¥${numPrice.toFixed(2)}`
}

// 定义项目接口类型
interface Project {
  id: number;
  name: string;
}

// 项目列表
const projectList = ref<Project[]>([])
// 获取项目列表
const getProjectList = async () => {
  try {
    const res = await getSimpleProject()
    if (res && res.data) {
      projectList.value = res.data
    }
  } catch (error) {
    console.error('获取项目列表失败:', error)
  }
}

// 堆垛机固定数据
const stackerData = ref([
  { name: '堆垛机数量', unit: '台', defaultValue: '1', price: 0, precision: 0,  remark: '' },
  { name: '货架高度', unit: 'm', defaultValue: '12', price: 0, precision: 0,  remark: '卷筒容绳量:' },
  { name: '提升行程', unit: 'm', defaultValue: '9.8', price: 0, precision: 2,  remark: '' },
  { name: '巷道长度', unit: 'm', defaultValue: '100', price: 0, precision: 0,  remark: '' },
  { name: '巷道宽度', unit: 'mm', defaultValue: '1550', price: 0, precision: 0,  remark: '' },
  { name: '长L', unit: 'm', defaultValue: '1.3', price: 0, precision: 0,  remark: '' },
  { name: '宽W', unit: 'm', defaultValue: '1.3', price: 0, precision: 0,  remark: '' },
  { name: '高H', unit: 'm', defaultValue: '1.2', price: 0, precision: 0,  remark: '' },
  { name: '货物重量', unit: 'kg', defaultValue: '500', price: 0, precision: 0,  remark: '' },
  { name: '货叉类型', unit: '/', defaultValue: '双指叉单伸', price: 0, precision: 0,  remark: '多叉不适用' },
  { name: '货叉重量', unit: 'kg', defaultValue: '300', price: 0, precision: 0,  remark: '建议手动输入' },
  { name: '满载行走速度', unit: 'm/min', defaultValue: '120', price: 0, precision: 0,  remark: '空载最大超频8%' },
  { name: '满载行走加速度', unit: 'm/s2', defaultValue: '0.3', price: 0, precision: 0,  remark: '空、满载一样' },
  { name: '行走轮直径', unit: 'mm', defaultValue: '315', price: 0, precision: 0, remark: '' },
  { name: '满载提升速度', unit: 'm/min', defaultValue: '30', price: 0, precision: 0,  remark: '空载最大超频15%' },
  { name: '满载提升加速度', unit: 'm/s2', defaultValue: '0.3', price: 0, precision: 0,  remark: '空载0.5' },
  { name: '卷筒直径', unit: 'mm', defaultValue: '298', price: 0, precision: 0,  remark: '' },
  { name: '卷筒形式', unit: '/', defaultValue: '无动滑轮', price: 0, precision: 0, remark: '' },
  { name: '载货台类型', unit: '/', defaultValue: 'YFM018', price: 0, precision: 0, remark: '' },
  { name: '立柱规格', unit: 'mm', defaultValue: '300×300×8', price: 0, precision: 0,  remark: '' },
  { name: '载货台重量', unit: 'kg', defaultValue: '772.4', price: 0, precision: 0, remark: '' },
  { name: '立柱重量', unit: 'kg', defaultValue: '2003.72928', price: 0, precision: 0, remark: '' },
  { name: '上下横梁重量', unit: 'kg', defaultValue: '1147.88', price: 0, precision: 0, remark: '' },
  { name: '附件重量', unit: 'kg', defaultValue: '1710', price: 0, precision: 0, remark: '' },
  { name: '提升总重', unit: 'kg', defaultValue: '1672.4', price: 0, precision: 0, remark: '' },
  { name: '行走总重过程', unit: 'kg', defaultValue: '6534.00928', price: 0, precision: 0, remark: '' },
  { name: '行走总重', unit: 'kg', defaultValue: '6534.00928', price: 0, precision: 0, remark: '' },
  { name: '钢丝绳直径', unit: 'mm', defaultValue: '12', price: 0, precision: 0,  remark: '' },
  { name: '需求转速', unit: 'r/min', defaultValue: '121.3224143', price: 0, precision: 0, remark: '' },
  { name: '需求扭矩', unit: 'Nm', defaultValue: '457.3806496', price: 0, precision: 0, remark: '' },
  { name: '需求功率', unit: 'kw', defaultValue: '5.810526144', price: 0, precision: 0, remark: '' },
  { name: '基频频率', unit: 'Hz', defaultValue: '87', price: 0, precision: 0,  remark: '可以不要，默认87HZ' },
  { name: '电机功率段', unit: 'kw', defaultValue: '4', price: 0, precision: 0,  remark: '' },
  { name: '电机型号', unit: '/', defaultValue: 'DR2S 100L4', price: 0, precision: 0, remark: '' },
  { name: '输出功率', unit: 'kw', defaultValue: '6.96', price: 0, precision: 0, remark: '可以不要' },
  { name: '额定转速', unit: 'r/min', defaultValue: '1445', price: 0, precision: 0, remark: '可以不要' },
  { name: '额定扭矩', unit: 'Nm', defaultValue: '26.5', price: 0, precision: 0, remark: '可以不要' },
  { name: '减速机型号', unit: '/', defaultValue: 'KA67', price: 0, precision: 0, remark: '' },
  { name: '行走电机', unit: '个', defaultValue: 'KA67DR2S 100L4', price: 0, precision: 0, remark: 'SEW' },
  { name: '需求转速2', unit: 'r/min', defaultValue: '121.3224143', price: 0, precision: 0, remark: '' },
  { name: '需求扭矩2', unit: 'Nm', defaultValue: '457.3806496', price: 0, precision: 0, remark: '' },
  { name: '需求功率2', unit: 'kw', defaultValue: '5.810526144', price: 0, precision: 0, remark: '' },
  { name: '基频频率2', unit: 'Hz', defaultValue: '87', price: 0, precision: 0, remark: '可以不要，默认87HZ' },
  { name: '电机功率段2', unit: 'kw', defaultValue: '7.5', price: 0, precision: 0, remark: '' },
  { name: '电机型号2', unit: '/', defaultValue: 'DR2S 100L4', price: 0, precision: 0, remark: '' },
  { name: '输出功率2', unit: 'kw', defaultValue: '6.96', price: 0, precision: 0, remark: '可以不要' },
  { name: '额定转速2', unit: 'r/min', defaultValue: '1445', price: 0, precision: 0, remark: '可以不要' },
  { name: '额定扭矩2', unit: 'Nm', defaultValue: '26.5', price: 0, precision: 0, remark: '可以不要' },
  { name: '减速机型号2', unit: '/', defaultValue: 'KA67', price: 0, precision: 0, remark: '' },
  { name: '提升电机', unit: '个', defaultValue: 'K97DR2S 132S4', price: 0, precision: 0, remark: 'SEW' },
  { name: '通讯方式', unit: '套', defaultValue: 'SICK光通讯', price: 0, precision: 0, remark: '' },
  { name: '定位方式', unit: '套', defaultValue: 'SICK激光', price: 0, precision: 0, remark: '激光范围：≤190m' },
  { name: 'PLC', unit: '套', defaultValue: '西门子1200', price: 0, precision: 0, remark: '' },
  { name: '变频器', unit: '套', defaultValue: '西门子', price: 0, precision: 0, remark: '' },
  { name: '光电开关', unit: '套', defaultValue: 'SICK光电', price: 0, precision: 0, remark: '' },
  { name: '堆垛机电控', unit: '套', defaultValue: '', price: 0, precision: 0, remark: '' },
  { name: '地面站数量', unit: '台', defaultValue: '有', price: 0, precision: 0, remark: '' },
  { name: '滑触线安装方式', unit: '/', defaultValue: '底部安装', price: 0, precision: 0, remark: '' },
  { name: '能效等级要求', unit: '/', defaultValue: '无', price: 0, precision: 0, remark: '' },
  { name: '当前钢材价格', unit: '元', defaultValue: '4000-4500', price: 0, precision: 0, remark: '' },
  
  { name: '以下为分项单价', unit: '', defaultValue: '', price: 0, precision: 0, remark: '' },
  { name: '机械本体', unit: '套', defaultValue: '自制', price: 0, precision: 0, remark: '' },
  { name: '行走电机', unit: '套', defaultValue: 'SEW', price: 0, precision: 0, remark: '' },
  { name: '提升电机', unit: '套', defaultValue: 'SEW', price: 0, precision: 0, remark: '' },
  { name: '货叉', unit: '套', defaultValue: '米亚斯', price: 0, precision: 0, remark: '' },
  { name: '电控', unit: '套', defaultValue: '自制', price: 0, precision: 0, remark: '' },
  { name: '机械安装调试', unit: '套', defaultValue: '', price: 0, precision: 0, remark: '第一台12000元，之后10000元/台' },
  { name: '电控安装调试', unit: '套', defaultValue: '', price: 0, precision: 0, remark: '第一台7000元，之后3500元/台' },
  { name: '使用环境', unit: '套', defaultValue: '常温', price: 0, precision: 0, remark: '机械*1.2，电控*1.3' },
  { name: '轨道类型', unit: '套', defaultValue: '直轨', price: 0, precision: 0, remark: '' },
  { name: '单机监控', unit: '套', defaultValue: '有', price: 0, precision: 0, remark: '' },
  { name: '巷道激光雷达', unit: '套', defaultValue: '无', price: 0, precision: 0, remark: '' },
  { name: '铠甲/灭火器', unit: '套', defaultValue: '无', price: 0, precision: 0, remark: '' },
  { name: '金属粉尘管控', unit: '套', defaultValue: '无', price: 0, precision: 0, remark: '' },
  { name: '其他非标', unit: '套', defaultValue: '', price: 0, precision: 0, remark: '' },
  { name: '单台', unit: '元', defaultValue: '', price: 0, precision: 1, remark: '' },
  { name: '合计', unit: '元', defaultValue: '', price: 0, precision: 1, remark: '' },
  { name: '条码带', unit: '米', defaultValue: '', price: 0, precision: 0, remark: '' },
  { name: '滑触线', unit: 'm', defaultValue: '瑞能', price: 0, precision: 0, remark: '' },
  { name: '滑触线护板', unit: 'm', defaultValue: '', price: 0, precision: 0, remark: '' },
  { name: '运输', unit: '车', defaultValue: '17.5米', price: 0, precision: 0, remark: '' }
])

// 获取规格参数表数据
const getSpecsTableData = () => {
  // 返回不包含"以下为分项单价"及其之后数据的表格数据
  const dividerIndex = stackerData.value.findIndex(item => item.name === '以下为分项单价')
  if (dividerIndex !== -1) {
    return stackerData.value.slice(0, dividerIndex)
  }
  return stackerData.value
}

// 获取分项单价表数据
const getPricingTableData = () => {
  // 返回"以下为分项单价"之后的数据作为第二个表格
  const dividerIndex = stackerData.value.findIndex(item => item.name === '以下为分项单价')
  if (dividerIndex !== -1) {
    return stackerData.value.slice(dividerIndex + 1)
  }
  return []
}

// 获取固定表格数据
const getFixedTableData = () => {
  return stackerData.value
}

// 更新汇总数据
const updateSummarizedData = () => {
  // 从表格中找到"单台"或"合计"字段的值作为总价
  const totalItem = stackerData.value.find(item => item.name === '合计')
  const barCodeItem = stackerData.value.find(item => item.name === '条码带')
  const slidingContactItem = stackerData.value.find(item => item.name === '滑触线')
  const slidingContactGuardItem = stackerData.value.find(item => item.name === '滑触线护板')
  
  if (totalItem && typeof totalItem.price === 'number') {
    // 使用"合计"字段的值，并加上条码带、滑触线、滑触线护板的价格
    let additionalCost = 0
    
    if (barCodeItem && typeof barCodeItem.price === 'number') {
      additionalCost += barCodeItem.price
    }
    
    if (slidingContactItem && typeof slidingContactItem.price === 'number') {
      additionalCost += slidingContactItem.price
    }
    
    if (slidingContactGuardItem && typeof slidingContactGuardItem.price === 'number') {
      additionalCost += slidingContactGuardItem.price
    }
    
    form.sumPrice = totalItem.price + additionalCost  // 已经是元为单位
  } else {
    // 如果没有找到总价字段，则计算所有有价格的项的总和
    let total = 0
    stackerData.value.forEach(item => {
      if (typeof item.price === 'number') {
        total += item.price  // 已经是元为单位
      }
    })
    form.sumPrice = total
  }
}



// 获取设备核价详情
const getDevicePricingDetail = async () => {
  if (!id.value) return
  
  try {
    const res = await getDevicePricingDetailApi(id.value)
    if (res && res.data) {
      // 确保数据类型转换正确
      const data = res.data
      
      // 基本信息赋值
      Object.assign(form, {
        id: data.id,
        projectId: data.projectId,
        projectName: data.projectName,
        type: data.type,
        sumPrice: data.sumPrice,
        remark: data.remark
      })
      
      // 如果是堆垛机类型，需要解析stackerData字段
      if (data.type === '堆垛机' && data.stackerData) {
        try {
          // 解析JSON字符串
          const parsedData = JSON.parse(data.stackerData)
          if (Array.isArray(parsedData) && parsedData.length > 0) {
            // 更新表格数据
            stackerData.value = parsedData
          }
        } catch (e) {
          console.error('解析堆垛机数据失败:', e)
        }
      } 
      // 兼容旧数据：如果没有stackerData但有detailItems，尝试从detailItems中恢复数据
      else if (data.type === '堆垛机' && data.detailItems && data.detailItems.length > 0) {
        // 遍历detailItems，更新stackerData中对应的值
        data.detailItems.forEach((item: any) => {
          const stackerItem = stackerData.value.find(sItem => sItem.name === item.materialCode)
          if (stackerItem) {
            stackerItem.price = item.quantity || 0
            stackerItem.defaultValue = item.specification || stackerItem.defaultValue
            stackerItem.remark = item.remark || stackerItem.remark
            if (item.nonStandard === '1') {
              stackerItem.color = 'red'
            }
          }
        })
      }
    }
  } catch (error) {
    console.error('获取设备核价详情失败:', error)
  }
}

// 获取设备类别字典
const getTypeOptions = async () => {
  try {
    const res = await getDictListApi({
      dictType: 'deviceType',
      dictName: "",
      status: undefined,
      page: 0,
      limit: 100
    })
    if (res && res.data) {
      typeOptions.value = res.data.list || []
    }
  } catch (error) {
    console.error('获取设备类别列表失败:', error)
  }
}

// 获取货叉类型字典
const getForkTypeOptions = async () => {
  try {
    const res = await getDictListApi({
      dictType: 'forkType',
      dictName: '',
      status: undefined,
      page: 0,
      limit: 100
    })
    if (res && res.data) {
      forkTypeOptions.value = res.data.list || []
    }
  } catch (error) {
    console.error('获取货叉类型字典失败:', error)
  }
}

// 批量获取方法
type DictTarget = typeof commTypeOptions
const getDictOptions = async (dictType: string, target: DictTarget) => {
  try {
    const res = await getDictListApi({
      dictType,
      dictName: '',
      status: undefined,
      page: 0,
      limit: 100
    })
    if (res && res.data) {
      target.value = res.data.list || []
    }
  } catch (error) {
    console.error(`获取${dictType}字典失败:`, error)
  }
}

// 更新计算的加载状态
const calculateLoading = ref(false)

// 保存表单的加载状态
const saveLoading = ref(false)

// 发送数据到后端计算价格
const calculatePricing = async () => {
  if (!form.type || form.type !== '堆垛机') {
    ElMessage.error('目前只支持堆垛机类型的设备核价')
    return
  }
  
  calculateLoading.value = true
  try {
    // 准备请求数据
    const requestData = {
      specsData: getSpecsTableData(),
      pricingData: getPricingTableData()
    }
    
    // 调用后端计算接口
    const res = await calculateStackerPricingApi(requestData)
    
    if (res && res.data) {
      // 解构返回的数据
      const { specsData, pricingData } = res.data
      
      // 更新规格参数表数据
      if (specsData && Array.isArray(specsData)) {
        const dividerIndex = stackerData.value.findIndex(item => item.name === '以下为分项单价')
        if (dividerIndex !== -1) {
          // 更新规格参数表部分
          stackerData.value.splice(0, dividerIndex, ...specsData)
        }
      }
      
      // 更新分项单价表数据
      if (pricingData && Array.isArray(pricingData)) {
        const dividerIndex = stackerData.value.findIndex(item => item.name === '以下为分项单价')
        if (dividerIndex !== -1) {
          // 更新分项单价表部分（保留分隔行）
          stackerData.value.splice(dividerIndex + 1, stackerData.value.length - dividerIndex - 1, ...pricingData)
        }
      }
      
      // 更新总价
      updateSummarizedData()
      
      ElMessage.success('计算完成')
    }
  } catch (error) {
    console.error('计算失败:', error)
    ElMessage.error('计算失败，请稍后重试')
  } finally {
    calculateLoading.value = false
  }
}

// 保存表格数据 (重命名为 saveTableData)
const saveTableData = async () => {
  if (!form.projectId) {
    ElMessage.error('请选择项目')
    return
  }
  
  if (!form.type || form.type !== '堆垛机') {
    ElMessage.error('目前只支持堆垛机类型的设备核价')
    return
  }
  
  // 计算总价
  updateSummarizedData()
  
  // 将堆垛机数据序列化为JSON字符串
  const stackerDataString = JSON.stringify(stackerData.value)
  
  saveLoading.value = true
  try {
    // 构建提交数据
    const formData = {
      ...form,
      projectId: form.projectId,
      type: form.type,
      stackerData: stackerDataString,  // 存储序列化的堆垛机数据
      detailItems: []  // 保持空数组，不再使用旧的明细结构
    }
    
    if (id.value) {
      // 更新
      await updateDevicePricingApi({
        ...formData,
        id: id.value
      })
      ElMessage.success('保存成功')
    } else {
      // 新增
      const res = await addDevicePricingApi(formData)
      if (res && res.data) {
        // 如果是新增成功，设置ID以便后续操作可以使用
        form.id = Number(res.data)
      }
      ElMessage.success('添加成功')
    }
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败，请稍后重试')
  } finally {
    saveLoading.value = false
  }
}

// 提交表单
const submitForm = () => {
  formRef.value?.validate(async (valid) => {
    if (!valid) return
    
    if (!form.projectId) {
      ElMessage.error('请选择项目')
      return
    }
    
    if (!form.type) {
      ElMessage.error('请选择设备类型')
      return
    }
    
    // 验证是否为堆垛机类型
    if (form.type !== '堆垛机') {
      ElMessage.error('目前只支持堆垛机类型的设备核价')
      return
    }
    
    // 计算总价
    updateSummarizedData()
    
    // 收集用户修改后的数据，用于后续数据更新或历史记录
    const userModifiedData: {
      defaultValues: Record<string, string | number>;
      prices: Record<string, number>;
    } = {
      defaultValues: {},
      prices: {}
    }
    
    // 遍历堆垛机数据，收集用户修改的值
    stackerData.value.forEach(item => {
      // 收集数值(满载)
      userModifiedData.defaultValues[item.name] = item.defaultValue
      
      // 收集价格(元)
      if (typeof item.price === 'number') {
        userModifiedData.prices[item.name] = item.price
      }
    })
    
    // 将堆垛机数据序列化为JSON字符串
    const stackerDataString = JSON.stringify(stackerData.value)
    
    submitLoading.value = true
    try {
      // 构建提交数据
      const formData = {
        ...form,
        projectId: form.projectId,
        type: form.type,
        stackerData: stackerDataString,  // 新增字段，存储序列化的堆垛机数据
        userModifiedData: JSON.stringify(userModifiedData),  // 存储用户修改的数据
        detailItems: []  // 保持空数组，不再使用旧的明细结构
      }
      
      if (id.value) {
        // 更新
        await updateDevicePricingApi({
          ...formData,
          id: id.value
        })
        ElMessage.success('更新成功')
      } else {
        // 新增
        await addDevicePricingApi(formData)
        ElMessage.success('添加成功')
      }
      goBack()
    } catch (error) {
      console.error('提交失败:', error)
      ElMessage.error('提交失败，请稍后重试')
    } finally {
      submitLoading.value = false
    }
  })
}

// 返回列表页
const goBack = () => {
  router.push('/devicePricing')
}

onMounted(async () => {
  await getTypeOptions()
  await getProjectList()
  await getForkTypeOptions()
  await getDictOptions('commType', commTypeOptions)
  await getDictOptions('positionType', positionTypeOptions)
  await getDictOptions('plcType', plcTypeOptions)
  await getDictOptions('inverterType', inverterTypeOptions)
  await getDictOptions('photoelectricType', photoelectricTypeOptions)
  await getDictOptions('stationNumType', stationNumOptions)
  await getDictOptions('slideLineInstallType', slideLineInstallOptions)
  await getDictOptions('motorEfficiencyType', motorEfficiencyOptions)
  await getDictOptions('steelPriceType', steelPriceOptions)
  // 新增分项单价表相关字典
  await getDictOptions('walkMotorType', walkMotorOptions)
  await getDictOptions('liftMotorType', liftMotorOptions)
  await getDictOptions('forkType2', forkOptions)
  await getDictOptions('envType', envOptions)
  await getDictOptions('railType', railTypeOptions)
  await getDictOptions('monitorType', monitorOptions)
  await getDictOptions('lidarType', lidarOptions)
  await getDictOptions('armorType', armorOptions)
  await getDictOptions('dustType', dustOptions)
  await getDictOptions('slideLineType', slideLineOptions)
  if (id.value) {
    await getDevicePricingDetail()
  } else if (form.type === '堆垛机') {
    // 如果是新增且类型为堆垛机，获取价格数据
  }
})
</script>

<style scoped lang="scss">
.device-pricing-form {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
  
  .box-card {
    margin-bottom: 20px;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .title {
        font-size: 18px;
        font-weight: 600;
      }
      
      .buttons {
        display: flex;
        gap: 10px;
      }
    }
  }
  
  .base-info-card,
  .device-details-card {
    margin-bottom: 20px;
    border: 1px solid #ebeef5;
    border-radius: 6px;
    
    .form-section-header {
      display: flex;
      align-items: center;
      gap: 8px;
      font-weight: 600;
      color: #409eff;
      
      .action-buttons {
        margin-left: auto;
        display: flex;
        gap: 10px;
      }
    }
  }
  
  .empty-table-tips {
    padding: 40px 0;
    background-color: #f8f8f8;
    border-radius: 4px;
    margin-bottom: 20px;
  }
  
  .device-details-table {
    width: 100%;
    margin-bottom: 20px;
  }
  
  .table-title {
    font-size: 16px;
    margin: 20px 0 10px;
    padding-left: 10px;
    border-left: 3px solid #409eff;
    font-weight: 600;
  }
  
  .pricing-title {
    border-left: 3px solid #f56c6c;
    margin-top: 30px;
  }
  
  .pricing-table {
    margin-bottom: 30px;
  }
  
  .table-actions {
    display: flex;
    justify-content: center;
    margin-bottom: 20px;
  }
  
  .summary-section {
    display: flex;
    justify-content: flex-end;
    padding: 16px 0;
    font-size: 16px;
    
    .summary-item {
      display: flex;
      align-items: center;
      gap: 10px;
      
      .label {
        font-weight: 600;
      }
      
      .value {
        font-size: 18px;
        color: #f56c6c;
        font-weight: 700;
      }
    }
  }
}

.full-width {
  width: 100%;
}

.material-dialog {
  :deep(.el-dialog) {
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
    
    .el-dialog__header {
      margin: 0;
      padding: 0;
    }
    
    .el-dialog__body {
      padding: 0;
    }
    
    .el-dialog__footer {
      padding: 12px 20px;
      border-top: 1px solid #ebeef5;
    }
  }

  .material-dialog-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px 20px;
    background: linear-gradient(135deg, #409eff, #1677ff);
    color: white;
    
    .dialog-title {
      display: flex;
      align-items: center;
      font-size: 16px;
      font-weight: 600;
      
      .dialog-icon {
        margin-right: 10px;
        font-size: 20px;
      }
    }
    
    .dialog-close {
      background: rgba(255, 255, 255, 0.2);
      border: none;
      
      &:hover {
        background: rgba(255, 255, 255, 0.3);
        transform: rotate(90deg);
        transition: all 0.3s;
      }
    }
  }
  
  .material-dialog-body {
    padding: 20px;
    max-height: 65vh;
    overflow-y: auto;
  }
  
  .material-dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    
    .el-button {
      padding: 9px 20px;
      
      &.el-button--primary {
        background: linear-gradient(135deg, #409eff, #1677ff);
        border: none;
        transition: all 0.3s;
        
        &:hover {
          opacity: 0.9;
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(24, 144, 255, 0.4);
        }
      }
    }
  }
}
</style>